<!-- build time:Tue Jul 21 2020 12:41:23 GMT+0800 (GMT+08:00) --><!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><meta name="generator" content="Hexo 4.2.0"><link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png"><link rel="icon" type="image/png" sizes="32x32" href="/img/blog_favicon/favicon-32x32-next.png"><link rel="icon" type="image/png" sizes="16x16" href="/img/blog_favicon/favicon-16x16-next.png"><link rel="mask-icon" href="/images/logo.svg" color="#222"><meta name="baidu-site-verification" content="r15J5zOS2KI43yBS"><link rel="stylesheet" href="/css/main.css"><link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"><link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css"><link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/themes/blue/pace-theme-minimal.min.css"><script src="//cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/pace.min.js"></script><script id="hexo-configurations">var NexT=window.NexT||{},CONFIG={hostname:new URL("http://www.zhengjiaao.cn").hostname,root:"/",scheme:"Muse",version:"7.6.0",exturl:!1,sidebar:{position:"left",display:"post",padding:18,offset:12,onmobile:!1},copycode:{enable:!0,show_result:!0,style:null},back2top:{enable:!0,sidebar:!1,scrollpercent:!0},bookmark:{enable:!0,color:"#222",save:"auto"},fancybox:!0,mediumzoom:!1,lazyload:!1,pangu:!1,comments:{style:"tabs",active:"valine",storage:!0,lazyload:!1,nav:null,activeClass:"valine"},algolia:{appID:"",apiKey:"",indexName:"",hits:{per_page:10},labels:{input_placeholder:"Search for Posts",hits_empty:"We didn't find any results for the search: ${query}",hits_stats:"${hits} results found in ${time} ms"}},localsearch:{enable:!0,trigger:"auto",top_n_per_article:1,unescape:!1,preload:!1},path:"search.xml",motion:{enable:!0,async:!1,transition:{post_block:"fadeIn",post_header:"slideDownIn",post_body:"slideDownIn",coll_header:"slideLeftIn",sidebar:"slideUpIn"}}}</script><meta property="og:type" content="article"><meta property="og:title" content="spring5-x-mongodb"><meta property="og:url" content="http://www.zhengjiaao.cn/posts/3173602028.html"><meta property="og:site_name" content="宇宙小神特别萌"><meta property="og:locale" content="zh_CN"><meta property="og:image" content="https://upload-images.jianshu.io/upload_images/15645795-4fe5474756e82313.png"><meta property="og:image" content="https://upload-images.jianshu.io/upload_images/15645795-ad1455ef1bddd12a.png"><meta property="og:image" content="https://upload-images.jianshu.io/upload_images/15645795-72195635b899736c.png"><meta property="article:published_time" content="2020-01-03T08:14:50.000Z"><meta property="article:modified_time" content="2020-07-20T10:37:55.311Z"><meta property="article:author" content="宇宙小神特别萌"><meta property="article:tag" content="spring5-xml方式配置"><meta name="twitter:card" content="summary"><meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/15645795-4fe5474756e82313.png"><link rel="canonical" href="http://www.zhengjiaao.cn/posts/3173602028.html"><script id="page-configurations">CONFIG.page={sidebar:"",isHome:!1,isPost:!0}</script><title>spring5-x-mongodb | 宇宙小神特别萌</title><noscript><style>.sidebar-inner,.use-motion .brand,.use-motion .collection-header,.use-motion .comments,.use-motion .menu-item,.use-motion .pagination,.use-motion .post-block,.use-motion .post-body,.use-motion .post-header{opacity:initial}.use-motion .site-subtitle,.use-motion .site-title{opacity:initial;top:initial}.use-motion .logo-line-before i{left:initial}.use-motion .logo-line-after i{right:initial}</style></noscript><link rel="alternate" href="/atom.xml" title="宇宙小神特别萌" type="application/atom+xml"></head><body itemscope itemtype="http://schema.org/WebPage"><div class="container use-motion"><div class="headband"></div><header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-container"><div class="site-meta custom-logo"><div class="site-meta-headline"><a><img class="custom-logo-image" src="/img/blog_favicon/favicon-32x32-next.png" alt="宇宙小神特别萌"></a></div><div><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">宇宙小神特别萌</span> <span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle">ZhengJa</p></div><div class="site-nav-toggle"><div class="toggle" aria-label="切换导航栏"><span class="toggle-line toggle-line-first"></span> <span class="toggle-line toggle-line-middle"></span> <span class="toggle-line toggle-line-last"></span></div></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">27</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">116</span></a></li><li class="menu-item menu-item-sitemap"><a href="/sitemap.xml" rel="section"><i class="fa fa-fw fa-sitemap"></i>站点地图</a></li><li class="menu-item menu-item-messageboard"><a href="/messageboard/" rel="section"><i class="fa fa-fw fa-address-book"></i>留言板</a></li><li class="menu-item menu-item-links"><a href="/links/" rel="section"><i class="fa fa-fw fa-user-plus"></i>友链</a></li><li class="menu-item menu-item-shuoshuo"><a href="/shuoshuo/" rel="section"><i class="fa fa-fw fa-file-text-o"></i>说说</a></li><li class="menu-item menu-item-search"><a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索</a></li></ul></nav><div class="site-search"><div class="popup search-popup"><div class="search-header"><span class="search-icon"><i class="fa fa-search"></i></span><div class="search-input-container"><input autocomplete="off" autocorrect="off" autocapitalize="none" placeholder="搜索..." spellcheck="false" type="text" id="search-input"></div><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span></div><div id="search-result"></div></div><div class="search-pop-overlay"></div></div></div></header><div class="back-to-top"><i class="fa fa-arrow-up"></i> <span>0%</span></div><div class="reading-progress-bar"></div><a role="button" class="book-mark-link book-mark-link-fixed"></a> <a href="https://github.com/zhengjiaao" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><main class="main"><div class="main-inner"><div class="content-wrap"><div class="content"><div class="posts-expand"><article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN"><link itemprop="mainEntityOfPage" href="http://www.zhengjiaao.cn/posts/3173602028.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="/my-images/avatar.gif"><meta itemprop="name" content="宇宙小神特别萌"><meta itemprop="description" content="人生就是一次幸运的旅行！"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="宇宙小神特别萌"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">spring5-x-mongodb</h1><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间：2020-01-03 16:14:50" itemprop="dateCreated datePublished" datetime="2020-01-03T16:14:50+08:00">2020-01-03</time> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="fa fa-calendar-check-o"></i> </span><span class="post-meta-item-text">更新于</span> <time title="修改时间：2020-07-20 18:37:55" itemprop="dateModified" datetime="2020-07-20T18:37:55+08:00">2020-07-20</time> </span><span id="/posts/3173602028.html" class="post-meta-item leancloud_visitors" data-flag-title="spring5-x-mongodb" title="热度"><span class="post-meta-item-icon"><i class="fa fa-eye"></i> </span><span class="post-meta-item-text">热度：</span> <span class="leancloud-visitors-count"></span> <span>℃</span> </span><span class="post-meta-item" title="热度" id="busuanzi_container_page_pv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-eye"></i> </span><span class="post-meta-item-text">热度：</span> <span id="busuanzi_value_page_pv"></span> </span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="fa fa-comment-o"></i> </span><span class="post-meta-item-text">Valine：</span> <a title="valine" href="/posts/3173602028.html#comments" itemprop="discussionUrl"><span class="post-comments-count valine-comment-count" data-xid="/posts/3173602028.html" itemprop="commentCount"></span></a></span><br><span class="post-meta-item" title="本文字数"><span class="post-meta-item-icon"><i class="fa fa-file-word-o"></i> </span><span class="post-meta-item-text">本文字数：</span> <span>19k</span> </span><span class="post-meta-item" title="阅读时长"><span class="post-meta-item-icon"><i class="fa fa-clock-o"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span>17 分钟</span></span></div></header><div class="post-body" itemprop="articleBody"><meta name="referrer" content="no-referrer"><p><img src="https://upload-images.jianshu.io/upload_images/15645795-4fe5474756e82313.png" alt="spring5.x-mongodb目录.png"></p><a id="more"></a><p>spring5x-mongodb 此模块是从spring5x-base 基础模块扩展过来的<br>spring5x-base模块是一个非常干净的spring5.x+springMVC架构<br>如果没有搭建spring5x-base模块 ，请参考 <a href="https://www.jianshu.com/p/8612404cf1d6" target="_blank" rel="noopener">spring5x-base模块搭建</a></p><h2 id="搭建项目"><a href="#搭建项目" class="headerlink" title="搭建项目"></a>搭建项目</h2><p><strong>基于spring5x-base 基础模块 新增功能：</strong></p><ul><li>1、spring5 mongodb 依赖及配置</li><li>2、MongoTemplate 对文档操作</li><li>3、GridFsTemplate 对文件操作</li><li>4、演示(文件上传和在线查看)</li></ul><h3 id="1、spring5-mongodb-依赖及配置"><a href="#1、spring5-mongodb-依赖及配置" class="headerlink" title="1、spring5 mongodb 依赖及配置"></a>1、spring5 mongodb 依赖及配置</h3><hr><p>pom.xml 依赖</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--MongoDB核心包--&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.mongodb<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mongodb-driver<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.6.4<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">scope</span>&gt;</span>compile<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.data<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-data-mongodb<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.0.10.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">scope</span>&gt;</span>compile<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">exclusions</span>&gt;</span></span><br><span class="line">              <span class="tag">&lt;<span class="name">exclusion</span>&gt;</span></span><br><span class="line">                  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mongo-java-driver<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">                  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.mongodb<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">              <span class="tag">&lt;/<span class="name">exclusion</span>&gt;</span></span><br><span class="line">              <span class="tag">&lt;<span class="name">exclusion</span>&gt;</span></span><br><span class="line">                  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jcl-over-slf4j<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">                  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.slf4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">              <span class="tag">&lt;/<span class="name">exclusion</span>&gt;</span></span><br><span class="line">              <span class="tag">&lt;<span class="name">exclusion</span>&gt;</span></span><br><span class="line">                  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>slf4j-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">                  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.slf4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">              <span class="tag">&lt;/<span class="name">exclusion</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;/<span class="name">exclusions</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- 其它的依赖(不包含spring) --&gt;</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">&lt;!--IOUtils工具使用--&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="comment">&lt;!--spring mvc的文件上传类 CommonsMultipartResolver 依赖了这个包--&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-fileupload<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-fileupload<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.3.3<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="comment">&lt;!-- 使用lombok实现JavaBean的get、set、toString、hashCode、equals等方法的自动生成  --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.16.18<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">scope</span>&gt;</span>provided<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">optional</span>&gt;</span>true<span class="tag">&lt;/<span class="name">optional</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure><p>mongodb.properties</p><figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># ip</span></span><br><span class="line"><span class="meta">mongo.host</span>=<span class="string">127.0.0.1</span></span><br><span class="line"><span class="comment"># 端口</span></span><br><span class="line"><span class="meta">mongo.port</span>=<span class="string">27017</span></span><br><span class="line"><span class="comment"># 数据库名称. 默认是'db'</span></span><br><span class="line"><span class="meta">mongo.dbname</span>=<span class="string">test</span></span><br><span class="line"><span class="comment"># 用户名</span></span><br><span class="line"><span class="meta">mongo.username</span>=<span class="string">test</span></span><br><span class="line"><span class="comment"># 密码</span></span><br><span class="line"><span class="meta">mongo.password</span>=<span class="string">123456</span></span><br><span class="line"><span class="comment"># 凭证：认证方式  用户:密码@数据库名称</span></span><br><span class="line"><span class="meta">mongo.credentials</span>=<span class="string">test:123456@test</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 每个主机允许的连接数</span></span><br><span class="line"><span class="meta">mongo.connectionsPerHost</span>=<span class="string">10</span></span><br><span class="line"><span class="comment"># 线程队列数 ，它和上面connectionsPerHost值相乘的结果就是线程队列最大值。如果连接线程排满了队列就会抛出异常</span></span><br><span class="line"><span class="meta">mongo.threadsAllowedToBlockForConnectionMultiplier</span>=<span class="string">5</span></span><br><span class="line"><span class="comment"># 连接超时的毫秒 0是默认值且无限大。</span></span><br><span class="line"><span class="meta">mongo.connectTimeout</span>=<span class="string">1000</span></span><br><span class="line"><span class="comment"># 最大等待连接的线程阻塞时间 默认是120000 ms (2 minutes).</span></span><br><span class="line"><span class="meta">mongo.maxWaitTime</span>=<span class="string">1500</span></span><br><span class="line"><span class="comment"># 保持活动标志 ，控制是否有套接字保持活动超时 官方默认为true 且不建议禁用</span></span><br><span class="line"><span class="meta">mongo.socketKeepAlive</span>=<span class="string">true</span></span><br><span class="line"><span class="comment"># 用于群集心跳的连接的套接字超时。</span></span><br><span class="line"><span class="meta">mongo.socketTimeout</span>=<span class="string">1500</span></span><br></pre></td></tr></table></figure><blockquote><p>注意：这里虽然有用户密码 ，但是我没有配置 ，应为我的mongodb没有设置用户密码认证</p></blockquote><p>spring-mongodb.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">" http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">" http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:context</span>=<span class="string">" http://www.springframework.org/schema/context"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:tx</span>=<span class="string">" http://www.springframework.org/schema/tx"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:mongo</span>=<span class="string">" http://www.springframework.org/schema/data/mongo"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">" http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context/spring-context.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/tx</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/tx/spring-tx.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/data/mongo</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/data/mongo/spring-mongo.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 加载mongodb的属性配置文件 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:property-placeholder</span> <span class="attr">location</span>=<span class="string">"classpath:mongodb/mongodb.properties"</span> <span class="attr">ignore-unresolvable</span>=<span class="string">"true"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--定义用于访问 MongoDB 的 MongoClient 实例 ,凭证：认证 credentials="$&#123;mongo.credentials&#125;" --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mongo:mongo-client</span> <span class="attr">id</span>=<span class="string">"mongoClient"</span> <span class="attr">host</span>=<span class="string">"$&#123;mongo.host&#125;"</span> <span class="attr">port</span>=<span class="string">"$&#123;mongo.port&#125;"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">mongo:client-options</span></span></span><br><span class="line"><span class="tag">                <span class="attr">connections-per-host</span>=<span class="string">"$&#123;mongo.connectionsPerHost&#125;"</span></span></span><br><span class="line"><span class="tag">                <span class="attr">threads-allowed-to-block-for-connection-multiplier</span>=<span class="string">"$&#123;mongo.threadsAllowedToBlockForConnectionMultiplier&#125;"</span></span></span><br><span class="line"><span class="tag">                <span class="attr">connect-timeout</span>=<span class="string">"$&#123;mongo.connectTimeout&#125;"</span></span></span><br><span class="line"><span class="tag">                <span class="attr">max-wait-time</span>=<span class="string">"$&#123;mongo.maxWaitTime&#125;"</span></span></span><br><span class="line"><span class="tag">                <span class="attr">socket-keep-alive</span>=<span class="string">"$&#123;mongo.socketKeepAlive&#125;"</span></span></span><br><span class="line"><span class="tag">                <span class="attr">socket-timeout</span>=<span class="string">"$&#123;mongo.socketTimeout&#125;"</span></span></span><br><span class="line"><span class="tag">        /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">mongo:mongo-client</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--- 方式一： --&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--&lt;mongo:repositories base-package="com.zja.dao.mongo"/&gt;--&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 方式二： --&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--定义用于连接到数据库的连接工厂--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mongo:db-factory</span> <span class="attr">dbname</span>=<span class="string">"$&#123;mongo.dbname&#125;"</span> <span class="attr">id</span>=<span class="string">"mongoDbFactory"</span> <span class="attr">mongo-ref</span>=<span class="string">"mongoClient"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--转换器--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mongo:mapping-converter</span> <span class="attr">id</span>=<span class="string">"converter"</span> <span class="attr">db-factory-ref</span>=<span class="string">"mongoDbFactory"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- mongodb的主要操作对象 ，所有对mongodb的增删改查的操作都是通过它完成 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"mongoTemplate"</span> <span class="attr">class</span>=<span class="string">"org.springframework.data.mongodb.core.MongoTemplate"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">name</span>=<span class="string">"mongoDbFactory"</span> <span class="attr">ref</span>=<span class="string">"mongoDbFactory"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--mongo存储文件：主要操作文件存储和下载--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"gridFsTemplate"</span> <span class="attr">class</span>=<span class="string">"org.springframework.data.mongodb.gridfs.GridFsTemplate"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">ref</span>=<span class="string">"mongoDbFactory"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">ref</span>=<span class="string">"converter"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure><p>spring-mvc.xml</p><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">" http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">" http://www.w3.org/2001/XMLSchema-instance"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:context</span>=<span class="string">" http://www.springframework.org/schema/context"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:mvc</span>=<span class="string">" http://www.springframework.org/schema/mvc"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">" http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd  http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc.xsd"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 开启注解包扫描--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:component-scan</span> <span class="attr">base-package</span>=<span class="string">"com.zja.*"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--使用默认的 Servlet 来响应静态文件 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mvc:default-servlet-handler</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 开启springMVC 注解驱动 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mvc:annotation-driven</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">mvc:message-converters</span> <span class="attr">register-defaults</span>=<span class="string">"false"</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!-- 将StringHttpMessageConverter的默认编码设为UTF-8  ，解决返回给前端中文乱码--&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.http.converter.StringHttpMessageConverter"</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">value</span>=<span class="string">"UTF-8"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!-- 将Jackson2HttpMessageConverter的默认格式化输出设为true --&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"prettyPrint"</span> <span class="attr">value</span>=<span class="string">"true"</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"supportedMediaTypes"</span>&gt;</span></span><br><span class="line">                    <span class="tag">&lt;<span class="name">list</span>&gt;</span></span><br><span class="line">                        <span class="comment">&lt;!-- 优先使用该媒体类型,为了解决IE浏览器下,返回JSON数据的下载问题 --&gt;</span></span><br><span class="line">                        <span class="tag">&lt;<span class="name">value</span>&gt;</span>application/json;charset=UTF-8<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">                        <span class="tag">&lt;<span class="name">value</span>&gt;</span>text/html;charset=UTF-8<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">                        <span class="tag">&lt;<span class="name">value</span>&gt;</span>text/json;charset=UTF-8<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">                    <span class="tag">&lt;/<span class="name">list</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">                <span class="comment">&lt;!-- 使用内置日期工具进行处理 --&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"objectMapper"</span>&gt;</span></span><br><span class="line">                    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"com.fasterxml.jackson.databind.ObjectMapper"</span>&gt;</span></span><br><span class="line">                        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dateFormat"</span>&gt;</span></span><br><span class="line">                            <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"java.text.SimpleDateFormat"</span>&gt;</span></span><br><span class="line">                                <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">type</span>=<span class="string">"java.lang.String"</span> <span class="attr">value</span>=<span class="string">"yyyy-MM-dd"</span>/&gt;</span></span><br><span class="line">                            <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">                        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">                    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">mvc:message-converters</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">mvc:annotation-driven</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 增加application.properties文件 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:property-placeholder</span></span></span><br><span class="line"><span class="tag">            <span class="attr">location</span>=<span class="string">"classpath:application.properties"</span> <span class="attr">ignore-unresolvable</span>=<span class="string">"true"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--spring-mongodb.xml 配置--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">import</span> <span class="attr">resource</span>=<span class="string">"classpath:mongodb/spring-mongodb.xml"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 配置视图解析器 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.web.servlet.view.InternalResourceViewResolver"</span></span></span><br><span class="line"><span class="tag">          <span class="attr">id</span>=<span class="string">"internalResourceViewResolver"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 前缀 ：/WEB-INF/jsp/和/WEB-INF/html/--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"prefix"</span> <span class="attr">value</span>=<span class="string">"/WEB-INF/jsp/"</span>/&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 后缀 ：.jsp和.html--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"suffix"</span> <span class="attr">value</span>=<span class="string">".jsp"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- =================== springmvc文件上传和下载 ================== --&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--配置文件上传 id值固定 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"multipartResolver"</span> <span class="attr">class</span>=<span class="string">"org.springframework.web.multipart.commons.CommonsMultipartResolver"</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 限制文件上传总大小 ，不设置默认没有限制 ，单位为字节 200*1024*1024即200M --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"maxUploadSize"</span> <span class="attr">value</span>=<span class="string">"209715200"</span> /&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 设置每个上传文件的大小上限 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"maxUploadSizePerFile"</span> <span class="attr">value</span>=<span class="string">"1048576"</span>/&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 处理文件名中文乱码 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"defaultEncoding"</span> <span class="attr">value</span>=<span class="string">"UTF-8"</span> /&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- resolveLazily属性启用是为了推迟文件解析 ，以便捕获文件大小异常 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"resolveLazily"</span> <span class="attr">value</span>=<span class="string">"true"</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure><blockquote><p>注：<br>1、spring-mongodb.xml 配置<br>2、multipartResolver 配置 是为了控制文件上传大小</p></blockquote><h3 id="2、MongoTemplate-对文档操作"><a href="#2、MongoTemplate-对文档操作" class="headerlink" title="2、MongoTemplate 对文档操作"></a>2、MongoTemplate 对文档操作</h3><hr><p>MongoTemplateController.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.zja.controller;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.mongodb.client.result.DeleteResult;</span><br><span class="line"><span class="keyword">import</span> com.zja.entity.UserDTO;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.MongoTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.query.Criteria;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.query.Query;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> ZhengJa</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span> Mongo 文档数据操作</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@data</span> 2019/11/8</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"rest/mongo"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MongoTemplateController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> MongoTemplate mongoTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"save/data"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">insert</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        UserDTO userDTO = <span class="keyword">new</span> UserDTO();</span><br><span class="line">        userDTO.setId(<span class="string">"1"</span>);</span><br><span class="line">        userDTO.setUsername(<span class="string">"1"</span>);</span><br><span class="line">        userDTO.setAge(<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//userDTO 要保存文档的数据  ，users集合    由于UserDTO类上有注解：@Document(collection = "users")</span></span><br><span class="line">        mongoTemplate.save(userDTO);</span><br><span class="line"></span><br><span class="line">        userDTO.setId(<span class="string">"2"</span>);</span><br><span class="line">        userDTO.setUsername(<span class="string">"2"</span>);</span><br><span class="line">        userDTO.setAge(<span class="number">2</span>);</span><br><span class="line">        <span class="comment">//userDTO 要保存文档的数据  ，users集合    由于UserDTO类上有注解：@Document(collection = "users")</span></span><br><span class="line">        mongoTemplate.save(userDTO);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//根据条件查询 注意是 _id   ，也可以用name等其它字段做条件</span></span><br><span class="line">        Query query = <span class="keyword">new</span> Query(Criteria.where(<span class="string">"_id"</span>).is(<span class="string">"2"</span>));</span><br><span class="line"></span><br><span class="line">        List&lt;UserDTO&gt; userDTOS = mongoTemplate.find(query, UserDTO<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> userDTOS;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据id查询users文档数据</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> java.lang.Object</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(value = <span class="string">"v2/users/getUser"</span>, method = RequestMethod.GET)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">getUser</span><span class="params">(@RequestParam String id)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//根据条件查询 注意是 _id   ，也可以用name等其它字段做条件</span></span><br><span class="line">        Query query = <span class="keyword">new</span> Query(Criteria.where(<span class="string">"_id"</span>).is(id));</span><br><span class="line"></span><br><span class="line">        List&lt;UserDTO&gt; userDTOS = mongoTemplate.find(query, UserDTO<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> userDTOS;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 查询所有users文档数据</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> java.lang.Object</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(value = <span class="string">"v2/users/getAllUser"</span>, method = RequestMethod.GET)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">getAllUser</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        List&lt;UserDTO&gt; userDTOS = mongoTemplate.findAll(UserDTO<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> userDTOS;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 删除单条users文档数据</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> java.lang.Object</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(value = <span class="string">"v2/users/deleteUser"</span>, method = RequestMethod.DELETE)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">deleteUser</span><span class="params">(@RequestParam String id)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//根据条件查询 注意是 _id   ，也可以用name等其它字段做条件</span></span><br><span class="line">        Query query = <span class="keyword">new</span> Query(Criteria.where(<span class="string">"_id"</span>).is(id));</span><br><span class="line"></span><br><span class="line">        DeleteResult deleteResult = mongoTemplate.remove(query, UserDTO<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line"></span><br><span class="line">        Map map = <span class="keyword">new</span> HashMap();</span><br><span class="line">        map.put(<span class="string">"wasAcknowledged"</span>, deleteResult.wasAcknowledged());</span><br><span class="line">        map.put(<span class="string">"getDeletedCount"</span>, deleteResult.getDeletedCount());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> map;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 删除所有users文档数据</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> java.lang.Object</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(value = <span class="string">"v2/users/deleteAllUser"</span>, method = RequestMethod.DELETE)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">deleteAllUser</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        Map map = <span class="keyword">new</span> HashMap();</span><br><span class="line">        List&lt;UserDTO&gt; userDTOS = (List&lt;UserDTO&gt;) getAllUser();</span><br><span class="line">        <span class="keyword">int</span> count = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (UserDTO userDTO : userDTOS) &#123;</span><br><span class="line">            Object o = deleteUser(userDTO.getId());</span><br><span class="line">            map.put(<span class="string">"删除的第几条数据-"</span> + count, o);</span><br><span class="line">            count++;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> map;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><blockquote><p>对文档的增删改查</p></blockquote><h3 id="3、GridFsTemplate-对文件操作"><a href="#3、GridFsTemplate-对文件操作" class="headerlink" title="3、GridFsTemplate 对文件操作"></a>3、GridFsTemplate 对文件操作</h3><hr><p>MongodbConfig.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.zja.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.mongodb.client.MongoDatabase;</span><br><span class="line"><span class="keyword">import</span> com.mongodb.client.gridfs.GridFSBucket;</span><br><span class="line"><span class="keyword">import</span> com.mongodb.client.gridfs.GridFSBuckets;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.MongoDbFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** Mongodb 配置类</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> zhengja@dist.com.cn</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@data</span> 2019/6/19 17:26</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MongodbConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> MongoDbFactory mongoDbFactory;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> GridFSBucket <span class="title">getGridFSBuckets</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        MongoDatabase db = mongoDbFactory.getDb();</span><br><span class="line">        <span class="keyword">return</span> GridFSBuckets.create(db);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><blockquote><p>操作文件：下载和在线查看文件 ，需要用的打开流</p></blockquote><p>GridFsTemplateController.java</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.zja.controller;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.mongodb.BasicDBObject;</span><br><span class="line"><span class="keyword">import</span> com.mongodb.DBObject;</span><br><span class="line"><span class="keyword">import</span> com.mongodb.client.gridfs.GridFSBucket;</span><br><span class="line"><span class="keyword">import</span> com.mongodb.client.gridfs.GridFSDownloadStream;</span><br><span class="line"><span class="keyword">import</span> com.mongodb.client.gridfs.model.GridFSFile;</span><br><span class="line"><span class="keyword">import</span> org.apache.commons.io.IOUtils;</span><br><span class="line"><span class="keyword">import</span> org.bson.types.ObjectId;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.query.Criteria;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.query.Query;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.gridfs.GridFsResource;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.gridfs.GridFsTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.http.MediaType;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestMapping;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestMethod;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestParam;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RestController;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.multipart.MultipartFile;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.annotation.Resource;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletResponse;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.io.InputStream;</span><br><span class="line"><span class="keyword">import</span> java.io.OutputStream;</span><br><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"><span class="keyword">import</span> java.util.UUID;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> ZhengJa</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span> 文件存储 操作</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@data</span> 2019/11/12</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"rest/gridfs"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GridFsTemplateController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> GridFsTemplate gridFsTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> GridFSBucket gridFSBucket;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**  文件上传测试：推荐用Postman工具请求测试 参考连接：https://www.jianshu.com/p/ba899556e02a **/</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**文件上传测试：推荐用Postman工具测试</span></span><br><span class="line"><span class="comment">     * 单文件上传到-mongodb</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> file</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> java.lang.String</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(value = <span class="string">"v1/save/file"</span>,method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">saveGridfs</span><span class="params">(@RequestParam(value = <span class="string">"file"</span>, required = <span class="keyword">true</span>)</span> MultipartFile file)</span>&#123;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"Saving file.."</span>);</span><br><span class="line">        DBObject metaData = <span class="keyword">new</span> BasicDBObject();</span><br><span class="line">        metaData.put(<span class="string">"createdDate"</span>, <span class="keyword">new</span> Date());</span><br><span class="line"></span><br><span class="line">        String fileName = UUID.randomUUID().toString();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"File Name: "</span> + fileName);</span><br><span class="line"></span><br><span class="line">        InputStream inputStream = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            inputStream = file.getInputStream();</span><br><span class="line">            gridFsTemplate.store(inputStream, fileName, <span class="string">"image"</span>, metaData);</span><br><span class="line">            System.out.println(<span class="string">"File saved: "</span> + fileName);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            System.out.println(<span class="string">"IOException: "</span> + e);</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"System Exception while handling request"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">"File return: "</span> + fileName);</span><br><span class="line">        <span class="keyword">return</span> fileName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/** 文件上传到mongodb：推荐用Postman工具测试</span></span><br><span class="line"><span class="comment">     * 多/单文件批量上传-mongodb :文件默认是上传到数据中的fs.files和fs.chunks中,files是用来存储文件的信息 ，文件名 ，md5,文件大小 ，还有刚刚的metadata,上传时间等等数据</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> multipartFiles</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> java.lang.Object</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(value = <span class="string">"v1/save/Manyfile"</span>, method = RequestMethod.POST)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">uploadManyFile1</span><span class="params">(@RequestParam(value = <span class="string">"file"</span>)</span> MultipartFile[] multipartFiles) <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        Map map = <span class="keyword">new</span> HashMap();</span><br><span class="line">        System.out.println(<span class="string">"multipartFiles.length "</span> + multipartFiles.length);</span><br><span class="line">        <span class="keyword">if</span> (multipartFiles != <span class="keyword">null</span> &amp;&amp; multipartFiles.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">int</span> count = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">for</span> (MultipartFile multipartFile : multipartFiles) &#123;</span><br><span class="line">                <span class="comment">// 获得提交的文件名</span></span><br><span class="line">                String fileName = multipartFile.getOriginalFilename();</span><br><span class="line">                <span class="comment">// 获得文件输入流</span></span><br><span class="line">                InputStream ins = multipartFile.getInputStream();</span><br><span class="line">                <span class="comment">// 获得文件类型</span></span><br><span class="line">                String contentType = multipartFile.getContentType();</span><br><span class="line">                <span class="comment">//存储文件的额外信息 ，比如用户ID,后面要查询某个用户的所有文件时就可以直接查询,可以不传</span></span><br><span class="line">                DBObject metadata = <span class="keyword">new</span> BasicDBObject(<span class="string">"userId"</span>, <span class="string">"1001"</span>);</span><br><span class="line"></span><br><span class="line">                <span class="comment">// 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息</span></span><br><span class="line">                ObjectId objectId = gridFsTemplate.store(ins, fileName, contentType);</span><br><span class="line"></span><br><span class="line">                <span class="comment">// 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息</span></span><br><span class="line">                <span class="comment">// ObjectId objectId = gridFsTemplate.store(ins, fileName, contentType, metadata);</span></span><br><span class="line"></span><br><span class="line">                String fileInfo = <span class="string">"文件名称:\n"</span>+fileName+<span class="string">"\n"</span>+<span class="string">"fileId:"</span>+<span class="string">"\n"</span>+objectId.toString()+<span class="string">"\n"</span>+<span class="string">"文件具体信息:\n"</span>+objectId;</span><br><span class="line"></span><br><span class="line">                map.put(<span class="string">"fileInfo"</span> + count,fileInfo);</span><br><span class="line"></span><br><span class="line">                count++;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> map;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 在线查看Mongo中的文件：根据名称获取文件并在线查看</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> fileName</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> response</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> int</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(value = <span class="string">"v1/get/file"</span>, method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getGridfs</span><span class="params">(@RequestParam(value = <span class="string">"fileName"</span>, required = <span class="keyword">true</span>)</span> String fileName,</span></span><br><span class="line"><span class="function">                         HttpServletResponse response) <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where(<span class="string">"filename"</span>).is(fileName)));</span><br><span class="line">        <span class="keyword">if</span> (gridFSFile==<span class="keyword">null</span>)&#123;</span><br><span class="line">            System.out.println(<span class="string">"File not found"</span> + fileName);</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"No file with name: "</span> + fileName);</span><br><span class="line">        &#125;</span><br><span class="line">        GridFsResource gridFsResource = convertGridFSFileToResource(gridFSFile);</span><br><span class="line">        <span class="keyword">return</span> IOUtils.copy(gridFsResource.getInputStream(),response.getOutputStream());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 下载Mongo文件：根据名称下载文件</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> fileName</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> response</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> int</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(value = <span class="string">"v1/download/file"</span>, method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">downloadGridfs</span><span class="params">(@RequestParam(value = <span class="string">"fileName"</span>, required = <span class="keyword">true</span>)</span> String fileName,</span></span><br><span class="line"><span class="function">                              HttpServletResponse response) <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where(<span class="string">"filename"</span>).is(fileName)));</span><br><span class="line">        <span class="keyword">if</span> (gridFSFile==<span class="keyword">null</span>)&#123;</span><br><span class="line">            System.out.println(<span class="string">"File not found"</span> + fileName);</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"No file with name: "</span> + fileName);</span><br><span class="line">        &#125;</span><br><span class="line">        GridFsResource gridFsResource = convertGridFSFileToResource(gridFSFile);</span><br><span class="line">        OutputStream sos = response.getOutputStream();</span><br><span class="line">        response.setCharacterEncoding(<span class="string">"UTF-8"</span>);</span><br><span class="line">        response.setHeader(<span class="string">"Access-Control-Allow-Origin"</span>, <span class="string">"*"</span>);</span><br><span class="line">        response.setContentType(<span class="string">"application/octet-stream"</span>);</span><br><span class="line">        response.addHeader(<span class="string">"Content-Disposition"</span>, <span class="string">"attachment; filename=\""</span> + fileName + <span class="string">"\""</span>);</span><br><span class="line">        <span class="keyword">return</span> IOUtils.copy(gridFsResource.getInputStream(),response.getOutputStream());</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 删除Mongo中的文件：根据名称删除文件</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> fileName 文件名</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> void</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RequestMapping</span>(value = <span class="string">"v1/delete/file"</span>, method = RequestMethod.DELETE)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteGridfs</span><span class="params">(@RequestParam(value = <span class="string">"fileName"</span>, required = <span class="keyword">true</span>)</span> String fileName) </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Deleting file.."</span> + fileName);</span><br><span class="line">        gridFsTemplate.delete(<span class="keyword">new</span> Query().addCriteria(Criteria.where(<span class="string">"filename"</span>).is(fileName)));</span><br><span class="line">        System.out.println(<span class="string">"File deleted "</span> + fileName);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 转换器：将GridFSFile转为GridFsResource</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> gridFsFile</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> org.springframework.data.mongodb.gridfs.GridFsResource</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> GridFsResource <span class="title">convertGridFSFileToResource</span><span class="params">(GridFSFile gridFsFile)</span> </span>&#123;</span><br><span class="line">        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFsFile.getObjectId());</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> GridFsResource(gridFsFile, gridFSDownloadStream);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><blockquote><p>对文件的操作：<br>1、上传单个文件到mongodb<br>2、上传多个或单个文件到mongodb<br>3、在线查看Mongo中的文件<br>4、下载Mongo文件<br>5、删除Mongo中的文件</p></blockquote><h3 id="4、演示-文件上传和在线查看"><a href="#4、演示-文件上传和在线查看" class="headerlink" title="4、演示(文件上传和在线查看)"></a>4、演示(文件上传和在线查看)</h3><hr><p>文件上传： <img src="https://upload-images.jianshu.io/upload_images/15645795-ad1455ef1bddd12a.png" alt="mongo_1.png"></p><hr><p>文件在线查看： <img src="https://upload-images.jianshu.io/upload_images/15645795-72195635b899736c.png" alt="mongo_2.png"></p><h2 id="github-地址："><a href="#github-地址：" class="headerlink" title="github 地址："></a>github 地址：</h2><ul><li><a href="https://links.jianshu.com/go?to=https%3A%2F%2Fgithub.com%2Fzhengjiaao%2Fspring5x" target="_blank" rel="noopener">https://github.com/zhengjiaao/spring5x</a></li></ul><h2 id="博客地址"><a href="#博客地址" class="headerlink" title="博客地址"></a>博客地址</h2><ul><li>简书：<a href="https://www.jianshu.com/u/70d69269bd09" target="_blank" rel="noopener">https://www.jianshu.com/u/70d69269bd09</a></li><li>掘金： <a href="https://juejin.im/user/5d82daeef265da03ad14881b/posts" target="_blank" rel="noopener">https://juejin.im/user/5d82daeef265da03ad14881b/posts</a></li></ul></div><div class="popular-posts-header"><p style="font-size:18px;color:red;margin:0 0 5px 0">相关文章推荐：</p></div><ul class="popular-posts"><li class="popular-posts-item"><div class="popular-posts-title"><a href="\posts\2680579140.html" rel="bookmark">Spring5x-base</a></div></li><li class="popular-posts-item"><div class="popular-posts-title"><a href="\posts\974023075.html" rel="bookmark">Spring5x-swagger2</a></div></li><li class="popular-posts-item"><div class="popular-posts-title"><a href="\posts\1894473216.html" rel="bookmark">spring5-x-memcached</a></div></li><li class="popular-posts-item"><div class="popular-posts-title"><a href="\posts\2137420170.html" rel="bookmark">spring5-x-rabbimq-高级篇</a></div></li><li class="popular-posts-item"><div class="popular-posts-title"><a href="\posts\2872074402.html" rel="bookmark">spring5-x-redis</a></div></li><li class="popular-posts-item"><div class="popular-posts-title"><a href="\posts\1537235376.html" rel="bookmark">spring5-x-rabbitmq-基础</a></div></li><li class="popular-posts-item"><div class="popular-posts-title"><a href="\posts\3838648753.html" rel="bookmark">spring5-x-springmvc</a></div></li><li class="popular-posts-item"><div class="popular-posts-title"><a href="\posts\2233938367.html" rel="bookmark">spring5x-data-jpa</a></div></li></ul><div><div style="text-align:center;color:#ccc;font-size:14px">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div></div><div class="reward-container"><div><p style="font-size:14px;color:#34495e;margin:0 0 5px 0">赞赏一下吧～ 还可以关注公众号订阅最新内容</p></div><button disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">打赏</button><div id="qr" style="display:none"><div style="display:inline-block"><img src="/my-images/WeChat.png" alt="宇宙小神特别萌 微信支付"><p>微信支付</p></div><div style="display:inline-block"><img src="/my-images/Alipay.png" alt="宇宙小神特别萌 支付宝"><p>支付宝</p></div></div></div><footer class="post-footer"><div class="post-tags"><a href="/tags/spring5-xml%E6%96%B9%E5%BC%8F%E9%85%8D%E7%BD%AE/" rel="tag"><i class="fa fa-tag"></i> spring5-xml方式配置</a></div><div class="post-nav"><div class="post-nav-item"><a href="/posts/2137420170.html" rel="prev" title="spring5-x-rabbimq-高级篇"><i class="fa fa-chevron-left"></i> spring5-x-rabbimq-高级篇</a></div><div class="post-nav-item"><a href="/posts/1894473216.html" rel="next" title="spring5-x-memcached">spring5-x-memcached <i class="fa fa-chevron-right"></i></a></div></div></footer></article></div></div><div class="comments" id="valine-comments"></div><script>window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }</script></div><div class="toggle sidebar-toggle"><span class="toggle-line toggle-line-first"></span> <span class="toggle-line toggle-line-middle"></span> <span class="toggle-line toggle-line-last"></span></div><aside class="sidebar"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc">文章目录</li><li class="sidebar-nav-overview">站点概览</li></ul><div class="post-toc-wrap sidebar-panel"><div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#搭建项目"><span class="nav-text">搭建项目</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1、spring5-mongodb-依赖及配置"><span class="nav-text">1、spring5 mongodb 依赖及配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2、MongoTemplate-对文档操作"><span class="nav-text">2、MongoTemplate 对文档操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3、GridFsTemplate-对文件操作"><span class="nav-text">3、GridFsTemplate 对文件操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4、演示-文件上传和在线查看"><span class="nav-text">4、演示(文件上传和在线查看)</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#github-地址："><span class="nav-text">github 地址：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#博客地址"><span class="nav-text">博客地址</span></a></li></ol></div></div><div class="site-overview-wrap sidebar-panel"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"><img class="site-author-image" itemprop="image" alt="宇宙小神特别萌" src="/my-images/avatar.gif"><p class="site-author-name" itemprop="name">宇宙小神特别萌</p><div class="site-description" itemprop="description">人生就是一次幸运的旅行！</div></div><div class="site-state-wrap motion-element"><nav class="site-state"><div class="site-state-item site-state-posts"><a href="/archives/"><span class="site-state-item-count">116</span> <span class="site-state-item-name">文章</span></a></div><div class="site-state-item site-state-tags"><a href="/tags/"><span class="site-state-item-count">27</span> <span class="site-state-item-name">标签</span></a></div></nav></div><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="https://github.com/zhengjiaao" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;zhengjiaao" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a> </span><span class="links-of-author-item"><a href="https://www.jianshu.com/u/70d69269bd09" title="简书 → https:&#x2F;&#x2F;www.jianshu.com&#x2F;u&#x2F;70d69269bd09" rel="noopener" target="_blank"><i class="fa fa-fw fa-book"></i>简书</a> </span><span class="links-of-author-item"><a href="/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-fw fa-rss"></i>RSS</a></span></div><div class="links-of-blogroll motion-element"><div class="links-of-blogroll-title"><i class="fa fa-fw fa-link"></i> 推荐阅读</div><ul class="links-of-blogroll-list"><li class="links-of-blogroll-item"><a href="https://github.com/spring-projects" title="https:&#x2F;&#x2F;github.com&#x2F;spring-projects" rel="noopener" target="_blank">spring-projects</a></li><li class="links-of-blogroll-item"><a href="http://www.alloyteam.com/nav/" title="http:&#x2F;&#x2F;www.alloyteam.com&#x2F;nav&#x2F;" rel="noopener" target="_blank">Web前端导航</a></li><li class="links-of-blogroll-item"><a href="http://www.chuangzaoshi.com/code" title="http:&#x2F;&#x2F;www.chuangzaoshi.com&#x2F;code" rel="noopener" target="_blank">创造狮导航</a></li></ul></div></div></div></aside><div id="sidebar-dimmer"></div></div></main><footer class="footer"><div class="footer-inner"><div class="copyright">&copy; <span itemprop="copyrightYear">2020</span> <span class="with-love"><i class="fa fa-heart"></i> </span><span class="author" itemprop="copyrightHolder">宇宙小神特别萌</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-area-chart"></i> </span><span title="站点总字数">1.2m</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-coffee"></i> </span><span title="站点阅读时长">17:41</span></div><div class="busuanzi-count"><script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span class="post-meta-item" id="busuanzi_container_site_uv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-user"></i> </span><span class="site-uv" title="总访客量"><span id="busuanzi_value_site_uv"></span> </span></span><span class="post-meta-divider">|</span> <span class="post-meta-item" id="busuanzi_container_site_pv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-eye"></i> </span><span class="site-pv" title="总访问量"><span id="busuanzi_value_site_pv"></span></span></span></div></div></footer></div><script src="//cdn.jsdelivr.net/npm/animejs@3.1.0/lib/anime.min.js"></script><script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script><script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/velocity/1.2.1/velocity.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/velocity/1.2.1/velocity.ui.min.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script><script src="/js/bookmark.js"></script><script>!function(){var t=document.createElement("script"),e=window.location.protocol.split(":")[0];t.src="https"===e?"https://zz.bdstatic.com/linksubmit/push.js":"http://push.zhanzhang.baidu.com/push.js";var s=document.getElementsByTagName("script")[0];s.parentNode.insertBefore(t,s)}()</script><script src="/js/local-search.js"></script><script>NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//cdnjs.cloudflare.com/ajax/libs/valine/1.3.10/Valine.min.js', () => {
    <!--var GUEST = ['nick', 'mail', 'link'];-->
    var GUEST = ['nick', 'mail'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el: '#valine-comments',
      verify: false,
      notify: false,
      appId: 'OuyHeA0XGL8hK4vgbqL0iERx-gzGzoHsz',
      appKey: 'L58VglKmWULcGK2W2AN7kWzM',
      placeholder: "留下邮箱，有回复时你将收到提醒，邮箱不会被公开。",
      avatar: 'wavatar',
      meta: guest,
      pageSize: '10' || 10,
      visitor: true,
      lang: 'zh-cn' || 'zh-cn',
      path: location.pathname,
      recordIP: true,
      serverURLs: ''
    });
  }, window.Valine);
});</script><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({pluginRootPath:"live2dw/",pluginJsPath:"lib/",pluginModelPath:"assets/",tagMode:!1,model:{jsonPath:"/live2dw/assets/wanko.model.json"},display:{position:"right",width:150,height:300},mobile:{show:!1},log:!1})</script></body><script type="text/javascript" src="/js/src/activetitle.js"></script></html><!-- rebuild by neat -->